package nb.photoviewer;

import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.Dragboard;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.TilePane;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import nb.photoviewer.slideshow.SlideController;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Deque;
import java.util.LinkedList;
import java.util.ResourceBundle;

//MainController 类实现了 Initializable 接口，这意味着它必须实现 initialize 方法，在该方法中进行初始化操作。
public class MainController implements Initializable {

    @FXML
    private TreeView<File> catalog;

    @FXML
    private ScrollPane scrollPane;

    @FXML
    private TilePane pictureArea;

    @FXML
    private Button slideShow;

    @FXML
    public Label attribute;

    @FXML
    private Button backFile;

    @FXML
    private Button advanceFile;

    @FXML
    private Button lastFile;

    @FXML
    private Button fresh;

    @FXML
    private Button copy;

    @FXML
    private Button paste;

    @FXML
    private Button delete;

    @FXML
    private TextField filePath;

    @FXML
    private TextField searchfield;//搜索框

    @FXML
    private Button ImageZoomIn;

    @FXML
    private Button ImageZoomOut;


    private TreeViewManager treeViewManager;
    private ImageDisplayManager imageDisplayManager;

    private Deque<File> directoryHistory;
    private Deque<File> backDirectoryHistory;


    //initialize 方法中首先创建了 TreeViewManager 和 ImageDisplayManager 的实例，用于管理目录树和图像显示区域。
    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        treeViewManager = new TreeViewManager(catalog);
        imageDisplayManager = new ImageDisplayManager(fresh,copy,delete,paste,pictureArea);
        imageDisplayManager.setCellFactory(catalog);
        imageDisplayManager.setMainController(this);
        imageDisplayManager.setTreeView(catalog); // 添加这行代码


        // 清空标签的内容
        attribute.setText("");

        initFileTreeView();

        fileAction();

        scrollPane.setFitToWidth(true); // TilePane的宽度将会扩展以适应ScrollPane的宽度
        scrollPane.setFitToHeight(true);

        setupSearchListener();//设置一个监听器，当搜索框内容改变时，会触发这个方法

        setupImageEnlargeListener();

        setupImageDwindleListener();

        filePath.setOnKeyPressed(event -> {
            if (event.getCode() == KeyCode.ENTER) {

            }
        });


    }





    //搜索框监听器
    private void setupSearchListener() {
        searchfield.textProperty().addListener((observable, oldValue, newValue) -> {
            String keyword = newValue.toLowerCase(); // 将搜索关键字转换为小写方便比较

            for (Node node : pictureArea.getChildren()) {
                if (node instanceof BorderPane) {
                    BorderPane borderPane = (BorderPane) node;
                    Label label = (Label) borderPane.getBottom();
                    String imageName = label.getText().toLowerCase(); // 获取图片名字并转换为小写

                    boolean shouldShow=imageName.contains(keyword);//Boolean表达式判断图片是否符合搜索要求，true/false
                    borderPane.setVisible(shouldShow);//符合搜索要求的图片可见，否则不可见
                    borderPane.setManaged(shouldShow);//不符合搜索要求的图片不可见，而且其不占用borderPane布局空间
                }
            }
        });

    }

    private void setupImageEnlargeListener(){
        //放大按钮监听器,修改ImageDisplayManager中imageView的大小
        ImageZoomIn.setOnAction(event -> {
            imageDisplayManager.zoomIn();
            System.out.println("放大");
        });

    }

    private void setupImageDwindleListener(){
        //缩小按钮监听器,修改ImageDisplayManager中imageView的大小
        ImageZoomOut.setOnAction(event -> {
            imageDisplayManager.zoomOut();
            System.out.println("缩小");
        });
    }

    private void fileAction() {
        directoryHistory = new LinkedList<>();
        backDirectoryHistory = new LinkedList<>();

        backFile.setOnAction(event -> {
            if (directoryHistory.size() > 1) {
                backDirectoryHistory.push(directoryHistory.pop());
                File previousDirectory = directoryHistory.peek();
                imageDisplayManager.displayImages(previousDirectory);
                imageDisplayManager.updateCurrentDirectory(previousDirectory);
                filePath.setText(previousDirectory.getAbsolutePath());
            }
        });

        advanceFile.setOnAction(event -> {
            if (!backDirectoryHistory.isEmpty()) {
                File nextDirectory = backDirectoryHistory.pop();
                directoryHistory.push(nextDirectory);
                imageDisplayManager.displayImages(nextDirectory);
                imageDisplayManager.updateCurrentDirectory(nextDirectory);
                filePath.setText(nextDirectory.getAbsolutePath());
            }
        });

        lastFile.setOnAction(event -> {
            File currentDirectory = directoryHistory.peek();
            if (currentDirectory != null) {
                File parentDirectory = currentDirectory.getParentFile();
                if (parentDirectory != null) {
                    directoryHistory.push(parentDirectory);
                    imageDisplayManager.displayImages(parentDirectory);
                    imageDisplayManager.updateCurrentDirectory(parentDirectory);
                    filePath.setText(parentDirectory.getAbsolutePath());
                }
            }
            });




    }

    private void initFileTreeView() {

        TreeItem<File> rootItem = new TreeItem<>(new File("我的电脑"));
        catalog.setRoot(rootItem);
        catalog.setShowRoot(true);
        File[] roots = File.listRoots();
        if (roots != null && roots.length > 0) {
            for (File root : roots) {
                TreeItem<File> item = new TreeItem<>(root);
                rootItem.getChildren().add(item);
                treeViewManager.createTree(root, item);
            }
        }
        rootItem.setExpanded(true);

        catalog.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue != null && newValue.getValue() != null) {
                File selectedDirectory = newValue.getValue();
                directoryHistory.push(selectedDirectory);
                backDirectoryHistory.clear();
                imageDisplayManager.updateCurrentDirectory(selectedDirectory);

                String imageAttributes = imageDisplayManager.getImageAttributes();
                attribute.setText(imageAttributes);
                filePath.setText(selectedDirectory.getAbsolutePath());
            }
        });


    }

    public class ImageGalleryController implements Initializable {

        @FXML
        private TextField searchField;

        @FXML
        private TilePane pictureArea;

        @Override
        public void initialize(URL location, ResourceBundle resources) {
            // 调用新方法setupSearchListener()来设置搜索功能的监听器
            setupSearchListener();
        }

        // 创建一个新的方法用于设置搜索功能的监听器
        private void setupSearchListener() {
            searchField.textProperty().addListener((observable, oldValue, newValue) -> {
                String keyword = newValue.toLowerCase(); // 将搜索关键字转换为小写方便比较

                for (Node node : pictureArea.getChildren()) {
                    if (node instanceof BorderPane) {
                        BorderPane borderPane = (BorderPane) node;
                        Label label = (Label) borderPane.getBottom();

                        String imageName = label.getText().toLowerCase(); // 获取图片名字并转换为小写

                        if (imageName.contains(keyword)) {
                            // 如果图片名字包含搜索关键字，显示对应的BorderPane
                            borderPane.setVisible(true);
                        } else {
                            // 如果图片名字不包含搜索关键字，隐藏对应的BorderPane
                            borderPane.setVisible(false);
                        }
                    }
                }
            });
        }
    }

    //幻灯片控件
    @FXML
    public void openSlideShowStage() throws Exception {
        //判断一下当前列表是否有图片，没有图片则不能打开幻灯片
        if(imageDisplayManager.getImageFiles().isEmpty()){
            return ;
        }
        //加载幻灯片界面的FXML文件
        FXMLLoader loader =new FXMLLoader(getClass( ).getResource("new-stage.fxml"));
        System.out.println(getClass( ).getResource("new-stage.fxml"));  //打印出路径

        try {
            Parent slideshowRoot = loader.load();
            //获取幻灯片控制器并初始化图片列表
            SlideController slideshowController = loader.getController();
            System.out.println(slideshowController);
            System.out.println("回到MainController,开始传imageFiles");
            //获取imageDisplayManager里存储的Files[]————这样就把文件数组传到slideshowController里了
            slideshowController.setImageFiles(imageDisplayManager.getImageFiles(),0);

            //创建和显示幻灯片界面的窗口
            Scene scene = new Scene(slideshowRoot);
            Stage slideshowStage = new Stage();
            slideshowStage.setScene(scene);
            slideshowStage.setTitle("幻灯片播放");

            // 设置图标
            Image slideshowIcon = new Image("file:src/main/resources/nb/photoviewer/img/幻灯片.png");
            slideshowStage.getIcons().add(slideshowIcon);

            //创建了一个新的场景，并将加载的FXML文件的根节点设置为该场景的根节点。
            // 设置Stage的最小宽度和高度
            slideshowStage.setMinWidth(900);
            slideshowStage.setMinHeight(620);

            slideshowStage.show();

            // 当新窗口关闭时执行的操作
            slideshowStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
                @Override
                public void handle(WindowEvent event) {
                    // 重新启用按钮
                    slideShow.setDisable(false);
                }
            });
            // 禁用按钮，避免多次点击
            slideShow.setDisable(true);
        }catch(IOException e) {
            e.printStackTrace();//处理异常
        }
    }


    public void openSlideShowStage(int index) throws Exception {
        //判断一下当前列表是否有图片，没有图片则不能打开幻灯片
        if(imageDisplayManager.getImageFiles().isEmpty()){
            return ;
        }
        //加载幻灯片界面的FXML文件
        FXMLLoader loader =new FXMLLoader(getClass( ).getResource("new-stage.fxml"));
        System.out.println(getClass( ).getResource("new-stage.fxml"));  //打印出路径

        try {
            Parent slideshowRoot = loader.load();
            //获取幻灯片控制器并初始化图片列表
            SlideController slideshowController = loader.getController();
            System.out.println(slideshowController);
            System.out.println("回到MainController,开始传imageFiles");
            //获取imageDisplayManager里存储的Files[]————这样就把文件数组传到slideshowController里了
            slideshowController.setImageFiles(imageDisplayManager.getImageFiles(),index);


            //创建和显示幻灯片界面的窗口
            Scene scene = new Scene(slideshowRoot);
            Stage slideshowStage = new Stage();
            slideshowStage.setScene(scene);
            slideshowStage.setTitle("幻灯片播放");

            //创建了一个新的场景，并将加载的FXML文件的根节点设置为该场景的根节点。
            // 设置Stage的最小宽度和高度
            slideshowStage.setMinWidth(900);
            slideshowStage.setMinHeight(620);

            slideshowStage.show();

            // 当新窗口关闭时执行的操作
            slideshowStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
                @Override
                public void handle(WindowEvent event) {
                    // 重新启用按钮
                    slideShow.setDisable(false);
                }
            });
            // 禁用按钮，避免多次点击
            slideShow.setDisable(true);
        }catch(IOException e) {
            e.printStackTrace();//处理异常
        }
    }

}